#include "offlinemsgmodel.hpp"
#include "db.hpp"

using namespace std;

static std::string server = "127.0.0.1";
static std::string dbuser = "root";
static std::string dbpwd = "123456";
static std::string dbname = "chat";

void OfflineMsgModel::insert(int userid, const std::string &msg)
{
    char sql[1024] = { 0 };
    sprintf(sql, "insert into offlinemessage values('%d', '%s')", userid, msg.c_str());

    MySQL mysql;
    if (mysql.connect(server, dbuser, dbpwd, dbname)) {
        mysql.update(sql);
    }
}

void OfflineMsgModel::remove(int userid)
{
    char sql[1024] = { 0 };
    sprintf(sql, "delete from offlinemessage where userid = '%d'", userid);

    MySQL mysql;
    if (mysql.connect(server, dbuser, dbpwd, dbname)) {
        mysql.update(sql);
    }
}

std::vector<std::string> OfflineMsgModel::query(int userid)
{
    char sql[1024] = { 0 };
    vector<string> messages;

    sprintf(sql, "select message from offlinemessage where userid = '%d'", userid);

    MySQL mysql;
    if (mysql.connect(server, dbuser, dbpwd, dbname)) {
        MYSQL_RES *res = mysql.query(sql);
        if (res) {
            MYSQL_ROW row;
            while (row = mysql_fetch_row(res)) {
                messages.push_back(row[0]);
            }
            mysql_free_result(res);
        }
    }    

    return messages;
}